/*


	jQuery plugin: formToggleControls
	Author: Ian Hart at Grand Union [ianh@thegrandunion.com]


	What?
	=====
	Disables/enables form elements.


	How?
	====
	This is a semi-custom plugin for the EON site and requires the following...
	
		HTML example:
		
			<input type="radio" class="toggle-off" name="my-example" id="my-radio-button-yes" />
			<input type="radio" class="toggle-on" name="my-example" id="my-radio-button-no" />
			
		CSS:
		
			input.disabled,
			select.disabled,
			label.disabled 		{ display:none; }
			
		JS:
		
			$().formToggleControls({
				'triggers' : $('#my-radio-button-yes, #my-radio-button-no'),
				'elements' : $('#my-triggered-element')
			});
			
			
	Options
	=======
	triggers: The elements used to trigger the disabling/enabling.
	elements: The elements to disable/enable.
	className: The CSS class applied to "elements".
	initApply: Apply the CSS class and disable "elements" on initialisation.
	
	
	Dependencies
	============
	- jQuery 1.3.2 or higher (jquery.com)


*/
(function($){

	$.fn.formToggleControls = function(settings){

		var config = {
				triggers : '',
				elements : '',
				className: 'disabled',
				initApply : true
			};
		
		if(settings){ $.extend(config, settings); }


		function init(el){
		
			if(config.triggers !== '' && config.elements !== ''){

				// Add the element's label to the array.
				config.elements = config.elements.add('label[for='+config.elements.attr('id')+']');

				if(config.initApply){
					config.elements.attr('disabled', 'disabled');
					config.elements.addClass(config.className);
				}
				
				// Are triggers already checked (from page refresh)? If so, toggle elements.
				config.triggers.each(function(){
					if($(this).is(':checked')){
						toggle(this);
					}
				});

				config.triggers.click(function(){
					toggle(this);
				});
				config.triggers.keypress(function(event){
					if(event.which==32){ toggle(this); }
				});
			
			}
		
		}
		
		
		function toggle(trigger){

			if($(trigger).hasClass('toggle-on')){
				config.elements.removeAttr('disabled');
				config.elements.removeClass(config.className);
			}
			else if($(trigger).hasClass('toggle-off')){
				config.elements.attr('disabled', 'disabled');
				config.elements.addClass(config.className);
			}
			else{
				if(config.elements.attr('disabled') === 'disabled'){
					config.elements.removeAttr('disabled');
				}
				else{
					config.elements.attr('disabled', 'disabled');
				}
				config.elements.toggleClass(config.className);
			}

		}
		
		
		init(this);
		return this;
	
	};

})(jQuery);